package drds.data_migrate.util;

import drds.common.$;
import drds.common.Author;
import drds.data_migrate.Authors;
import drds.data_migrate.TableSplits;
import drds.data_migrate.vo.ConnectionInfo;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

@Slf4j
@Author(name = Authors.LI_YANG)
public class TableCheckTask implements Callable<Boolean>
{
    private ConnectionInfo connectionInfo;

    public TableCheckTask(ConnectionInfo connectionInfo)
    {
        this.connectionInfo = connectionInfo;

    }


    public Boolean call() throws SQLException
    {
        String jdbcUrl = this.connectionInfo.getJdbcUrl();
        List<String> querySqlList = this.connectionInfo.getQuerySqlList();
        List<String> splitColumnRangeSqlList = this.connectionInfo.getSplitColumnRangeSqlList();

        Connection connection = Jdbc.getConnection(jdbcUrl, this.connectionInfo.getUsername(), this.connectionInfo.getPassword());
        int fetchSize = Integer.MIN_VALUE;
        try
        {

            /*verify executeQuery*/

            ResultSet resultSet = null;
            try
            {

                resultSet = Jdbc.executeQuery(connection, querySqlList.get(0), fetchSize);
            } catch (SQLException e)
            {
                log.error($.printStackTraceToString(e));
                return false;
            } finally
            {
                Jdbc.close(resultSet, null, null);
            }
                /*verify splitPK*/

            try
            {
                if ($.isHasData(splitColumnRangeSqlList))
                {
                    TableSplits.getMinMaxValuePair(connection, splitColumnRangeSqlList.get(0));
                }
            } catch (Exception e)
            {
                log.error($.printStackTraceToString(e));
                return false;
            }
        } finally
        {
            Jdbc.close(null, connection);
        }
        return true;
    }
}
